<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<link rel="stylesheet" href="dists/input-tags/css/inputTags.css" />
		<style>
			
			.panel-tool a{font-size: 14px; height: 14px; vertical-align: super;}
			
			#categoryEditForm .form-item , .productInfo-text .form-item {margin-bottom: 18px;}
			#categoryEditForm .form-item>label , .productInfo-text .form-item>label{min-width: 72px; display: inline-block; text-align: right;}
			
			.createProductForm{text-align: center;margin-top: 20px;}			
			.edit-title{display: block; margin-bottom: 8px; font-weight: bold; border-bottom: 1px solid #D3D3D3; padding: 4px;}
			.productInfo{box-sizing: border-box; height: 420px; display: flex;justify-content: center;}
			.productInfo .productInfo-images{display: inline-block; width: 400px; box-sizing: border-box; position: relative;}
			.productInfo .productInfo-images a.image-delete{position: absolute; top: 10px; right: 0px; color: #FF0000;}
			.productInfo .productInfo-images a.image-delete:hover{opacity: 0.8;}
			.productInfo .productInfo-images img.primary{width: 350px; height: 350px;}
			.productInfo .productInfo-images div.images{display: flex;margin-top: 2px;overflow: auto;}
			.productInfo .productInfo-images div.images .img-con{box-sizing: border-box;padding: 2px; position: relative;}
			.productInfo .productInfo-images div.images img{display: inline-block; box-sizing: border-box;padding: 2px; width: 70px; height: 70px;}
			.productInfo .productInfo-images div.images img.active{background: #000;}
			.productInfo .productInfo-images div.images img:first-child{padding-left: 0px;}
			.productInfo .productInfo-images div.images img:last-child{padding-right: 0px;}
			.productInfo .productInfo-text{display: inline-block; width: 400px; box-sizing: border-box; padding: 0px 15px;}
			
			
			.productProps{text-align: center; margin: 0px auto;}
			.productDetails{text-align: center;  margin: 0px auto;}
			
			
			.attribute-panel{box-sizing: border-box; border: 1px solid #CFCFCF; margin-bottom: 15px;}
			.attribute-panel .attribute-panel-header{box-sizing: border-box;display: flex;justify-content: space-between;font-weight: bold;padding: 8px; background: #F3F3F3;}
			.attribute-panel .attribute-panel-header > span:last-child{cursor: pointer;}
			.attribute-panel .attribute-panel-header > span:last-child:hover{opacity: 0.8;}
			.attribute-panel .attribute-panel-body{box-sizing: border-box; padding: 8px;}

			.batchEditProductForm label{text-align: right;}
			.batchEditProductForm .form-item{text-align: center;}

			.img-con-add{min-width: 70px; height: 70px; line-height: 70px; text-align: center;}
			.w-e-text img{max-width: 90%;}
			.w-e-text table{margin: 0px auto;}
			
			.product-set-container{}
			.product-set-container .product-set-item{margin-bottom: 8px;}
			.product-set-container .product-set-item .product-set-item-delete{margin-left: 16px; cursor: pointer; color: #FF0000;}
			
			.w-e-text img{width: 80% !important;}
			
			.panel-tool a.customer1{font-size: 18px; opacity: 1; margin-left: 8px;}
			
		</style>
		<div class="super-theme-example">
			<div class="easyui-layout" style="width:100%;height:100%;">
				<div id="p" data-options="region:'west',collapsible:false" title="分类" style="width:250px;padding:10px">
					<ul id="category-tree"></ul>
				</div>
				<div data-options="region:'center',collapsible:false" title="商品" style="padding:10px">
					<div class="options-toolbar">
						<form id="productDatagridQueryParams">
							<input class="easyui-textbox" name="productId" data-options="width:80,prompt:'商品ID'">
							<input class="easyui-textbox" name="tags" data-options="width:120,prompt:'商品标签'">
							<input class="easyui-textbox" name="comments" data-options="width:120,prompt:'商品备注'">
							<input class="easyui-textbox" name="productTitle" data-options="width:120,prompt:'商品名称'">
							<select id="sourceTypeCombo" class="easyui-combobox" name="status" style="width:120px;">
							    <option value="">全部状态</option>
							    <option value="-1">创建失败</option>
							    <option value="0">创建中</option>
							    <option value="1">创建成功</option>
							    <option value="10">上线中</option>
							    <option value="-10">已下线</option>
							</select>
							<select id="sourceTypeCombo" class="easyui-combobox" name="sourceType" style="width:120px;">
							    <option value="">全部来源</option>
							    <option value="tmall">TMALL</option>
							    <option value="taobao">TAOBAO</option>
							    <option value="1688">1688</option>
							    <option value="other">其他</option>
							</select>
							<input id="supplierCombo" name="supplierId">
							
							<input id="product-datepicker" class="datepicker-input" />
							
							<a href="javascript:void(0)" class="easyui-linkbutton primary" data-options="iconCls:'fa fa-search'" onclick="app_product_list.methods.queryDatagrid();"></a>
						</form>
						
						<div class="top-options">
							<a href="javascript:void(0)" class="easyui-menubutton info" data-options="menu:'#product_list_tools'">操作</a>
							<div id="product_list_tools" style="width:120px;">
								<div data-options="iconCls:'fa fa-plus'" onclick="$('#createProductDialog').dialog('open');$('#productIds').textbox('clear')">新建</div>
								<div data-options="iconCls:'fa fa-edit'" onclick="app_product_list.methods.batchEditParame();">批量编辑</div>
								<div class="menu-sep"></div>
								<div data-options="iconCls:'fa fa-arrow-up'" onclick="app_product_list.methods.upProducts();">批量上架</div>
								<div data-options="iconCls:'fa fa-arrow-down'" onclick="app_product_list.methods.downProducts();">批量下架</div>
								<div class="menu-sep"></div>
								<div data-options="iconCls:'fa fa-download'" onclick="exportExcel(commonConfig.shopUrlPrefix() + '/product/list/export-fb' , app_product_list.methods.initDatagridQueryParams())">DPA</div>
							</div>
						</div>
					</div>
					<table id="product-datagrid" style="width: 100%;"></table>
				</div>
			</div>
			
			<div id="categoryMenu" class="easyui-menu" data-options="onClick:app_product_list.methods.categoryMenuHandler" style="width:120px;">
				<div data-options="name:'add',iconCls:'fa fa-plus'">新增子分类</div>
				<div data-options="name:'edit',iconCls:'fa fa-edit'">修改</div>
				<div class="menu-sep"></div>
				<div data-options="name:'delete',iconCls:'fa fa-trash-o'">删除</div>
			</div>
			
			<div id="categoryEditWin" class="easyui-window" title="分类" style="width:400px;height:300px" data-options="modal:true,closed:true,minimizable:false,maximizable:false">
				<div class="super-theme-example">
					<form id="categoryEditForm">
						<input name="id" type="hidden">
						<input name="parentId" type="hidden">
						<div class="form-item">
							<label for="" class="label-top">名称：</label>
							<input name="name" class="easyui-textbox" style="width: 250px;" prompt="分类名称...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">优先级：</label>
							<input name="priority" class="easyui-numberbox" value="0" data-options="min:0" style="width: 250px;" prompt="优先级...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">备注：</label>
							<input name="comments" class="easyui-textbox" data-options="multiline:true" style="width: 250px;" prompt="备注...">
						</div>
					</form>
					<div style="text-align: right; box-sizing: border-box;padding: 10px;">
						<a href="#" class="easyui-linkbutton" style="width: 80px;" onclick="$('#categoryEditWin').window('close');">取消</a>
						<a href="#" class="easyui-linkbutton primary" style="width: 80px;" onclick="app_product_list.methods.editCategorySubimt();">保存</a>
					</div>
				</div>
			</div>
	
			<div id="productBatchParame" class="easyui-dialog" title="批量编辑" style="width:500px;height:550px;padding: 10px;" data-options="modal:true,shadow:true,closed:true,buttons: [{
					text:'确定',
					handler: function(){
						app_product_list.methods.saveBatchEditParame()
					}
				},{
					text:'取消',
					handler:function(){
						$('#productBatchParame').dialog('close');
					}
				}]">
				<form class="batchEditProductForm">
					<div class="form-item">
						<label for="title">标题：</label>
						<input name="title" class="easyui-textbox" data-options="prompt:'请输入标题...',type:'text'" style="width: 350px;"><br/><br/>
					</div>
					<div class="form-item">
						<label for="description">描述：</label>
						<input name="description" class="easyui-textbox" data-options="prompt:'请输入描述...',type:'text'" style="width: 350px;"><br/><br/>
					</div>
					<div class="form-item">
						<label for="tags">标签：</label>
						<input name="tags" class="easyui-textbox" data-options="prompt:'请输入标签...',type:'text'" style="width: 350px;"><br/><br/>
					</div>
					<div class="form-item">
						<label for="price">售价：</label>
						<input name="price" class="easyui-numberbox" data-options="min:0,precision:0" style="width: 350px;" prompt="售价..."><br/><br/>
					</div>
					<div class="form-item">
						<label for="originalPrice">原价：</label>
						<input name="originalPrice" class="easyui-numberbox" data-options="min:0,precision:0" style="width: 350px;" prompt="原价..."><br/><br/>
					</div>
					<div class="form-item">
						<label for="batchEditProductCategoryId">分类：</label>
						<select id="batchEditProductCategoryId" name="categoryId" class="easyui-combobox" style="width: 350px;"></select><br/><br/>
					</div>
					<div class="form-item" style="text-align: left; box-sizing: border-box; padding-left: 45px;">
						<label for="originalPrice">蒙层：</label>
						<img onclick="app_product_list.datas.uploaderUploadCallBack = app_product_list.methods.batchEditUploadCoverCallBack; $('#prodfuctChangeImage').trigger('click');" class="product-cover-img" style="border: 1px solid #FFF; width: 100px;" src="dists/imgs/upload_placeholder.png" />
					</div>
				</form>
			</div>

			<div id="createProductDialog" class="easyui-dialog" title="创建产品" style="width:600px;height:400px;" data-options="modal:true,shadow:true,closed:true,buttons: [{
					text:'确定',
					handler:function(){
						app_product_list.methods.createProduct();
						$('#createProductDialog').dialog('close');
					}
				},{
					text:'取消',
					handler:function(){
						$('#createProductDialog').dialog('close');
					}
				}]">
				<form class="createProductForm">
			    	<div class="form-item">
			    		<select id="create-sourceType" class="easyui-combobox" name="sourceType" style="width:500px;">
						    <option value="1688">1688</option>
						    <option value="tmall">TMALL</option>
						    <option value="taobao">TAOBAO</option>
						    <option value="pdd">PDD</option>
						</select>
			    	</div>
					<div class="form-item">
						<input id="create-productIds" class="easyui-textbox" data-options="prompt:'输入产品ID,逗号分隔...',type:'text',multiline:true" style="width: 500px; height: 200px;"><br/><br/>
					</div>
				</form>
			</div>
			
			<div id="productEdit" class="easyui-window" title="产品编辑" style="width:1400px;height:900px" data-options="modal:true,collapsible:false,closable:false,minimizable:false,closed:true,maximizable:false,tools:[{iconCls:'fa fa-save customer1',handler:function(){app_product_list.methods.saveProduct();}},{iconCls:'fa fa-close customer1',handler:function(){$('#productEdit').window('close');}}]">
				<div class="super-theme-example" style="padding: 20px 120px;">
					<div class="productInfoBox">
						<span class="edit-title">信息</span>
						<div class="productInfo">
							<div class="productInfo-images"></div>
							<button type="button" id="prodfuctChangeImage" style="display: none;"></button>
							
							<div class="productInfo-text">
								<form>
									<div class="form-item">
										<label for="" class="label-top">标题：</label>
										<input id="title" name="title" class="easyui-textbox" style="width: 290px;" prompt="标题...">
									</div>
									<div class="form-item">
										<label for="" class="label-top">售价：</label>
										<input id="price" name="price" class="easyui-numberbox" data-options="min:0,precision:0" style="width: 105px;" prompt="售价...">
										<label for="" class="label-top">原价：</label>
										<input id="originalPrice" name="originalPrice" class="easyui-numberbox" data-options="min:0,precision:0" style="width: 105px;" prompt="原价...">
									</div>
									<div class="form-item">
										<label for="" class="label-top">描述：</label>
										<input id="description" name="description" class="easyui-textbox" style="width: 290px;" prompt="描述...">
									</div>
									<div class="form-item">
										<label for="" class="label-top">标签：</label>
										<input id="tags" name="tags" class="easyui-textbox" style="width: 290px;" prompt="标签...">
									</div>
									<div class="form-item">
										<label for="" class="label-top">货号：</label>
										<input id="sourceNumber" name="sourceNumber" class="easyui-textbox" style="width: 290px;" prompt="货号...">
									</div>
									<div class="form-item">
										<label for="" class="label-top">原始链接：</label>
										<input id="sourceUrl" name="sourceUrl" class="easyui-textbox" style="width: 290px;" prompt="原始链接...">
									</div>
									<div class="form-item">
										<label for="" class="label-top">产品分类：</label>
										<select id="categoryId" name="categoryId" class="easyui-combobox" style="width: 290px;"></select>
									</div>
									<div class="form-item">
										<label for="" class="label-top">备注：</label>
										<input id="comments" name="comments" class="easyui-textbox" data-options="multiline:true" style="width: 290px; height: 60px;" prompt="备注...">
									</div>
								</form>
							</div>
						</div>
					</div>
					
					<div class="productPropsBox">
							<span class="edit-title">属性页</span>
							<div class="productProps" ></div>
						</div>
						
					<div class="productDetailsBox">
						<span class="edit-title">详情页</span>
						<div class="productDetails"></div>
					</div>
					
					<div class="productAttrBox">
						<span class="edit-title">属性</span>
						<div class="productAttribute"></div>
					</div>
					
					<div class="productSkuBox" style="margin-bottom: 20px;">
						<span class="edit-title">SKU</span>
						<table id="productSku-datagrid" style="height: 600px;"></table>
					</div>
				</div>
			</div>
			
			<div id="productComments" class="easyui-window" title="产品评论" style="width:1200px;height:800px" data-options="modal:true,minimizable:false,closed:true,maximizable:false">
				<table id="product-comments-datagrid"></table>
			</div>
			
			<div id="productCommentsPersit" class="easyui-window" title="产品评论" style="width:500px;height:400px" data-options="modal:true,minimizable:false,closed:true,maximizable:false">
				<form id="productCommentsPersit-form">
					<div class="form-item" style="margin-top: 10px;">
						<label for="" class="label-top" style="width: 100px; display: inline-block; text-align: right;">用户名：</label>
						<input name="userName" class="easyui-textbox" style="width: 290px;" prompt="用户名...">
					</div>
					<div class="form-item" style="margin-top: 10px;">
						<label for="" class="label-top" style="width: 100px; display: inline-block; text-align: right;">备注：</label>
						<input name="comments" class="easyui-textbox" data-options="multiline:true" style="width: 290px; height: 60px;" prompt="评论...">
					</div>
					<div class="form-item" style="margin-top: 10px;">
						<label for="" class="label-top" style="width: 100px; display: inline-block; text-align: right;">时间：</label>
						<input name="commentsAt" class="easyui-datetimebox" style="width:290px; height: 32px;">
					</div>
					<div class="form-item" style="margin-top: 10px;">
						<label for="" class="label-top" style="width: 100px; display: inline-block; text-align: right;">图片：</label>
						<img onclick="app_product_list.datas.uploaderUploadCallBack = function(result){$('.product-comments-img').attr('src' , JSON.parse(result.response).datas[0]);}; $('#prodfuctChangeImage').trigger('click');" class="product-comments-img" style="border: 1px solid #FFF; width: 100px;" src="dists/imgs/upload_placeholder.png" />
					</div>
				</form>
				<a href="#" class="easyui-linkbutton primary" onclick="app_product_list.methods.productCommentsPersit()" style="width: 340px; margin-top: 20px; margin-left: 60px;" data-options="iconCls:'fa fa-save'">保存</a>
			</div>
			
			
			<div id="productSetWindow" class="easyui-dialog" title="产品套餐" style="width:500px;height:550px;padding: 10px;" data-options="modal:true,shadow:true,closed:true,buttons: [{
					text:'确定',
					handler: function(){
						app_product_list.sets.saveItems();
					}
				},{
					text:'取消',
					handler:function(){
						$('#productSetWindow').dialog('close');
					}
				}],tools: [
					{
						iconCls:'fa fa-plus',
						handler:app_product_list.sets.addItem
					}
				]">
				
				<div class="product-set-container"></div>
			</div>
		</div>
		<script src="dists/wangEditor/release/wangEditor.js"></script>
		<script src="dists/input-tags/js/inputTags.jquery.js"></script>
		<script src="dists/super/js/ddsort.js"></script>
		<script type="text/javascript" src="dists/plupload-2.3.6/js/plupload.full.min.js"></script>
		<script type="text/javascript" src="dists/plupload-2.3.6/js/i18n/zh_CN.js"></script>
		<script type="text/javascript">
			var app_product_list = {
				datas : {
					contextMenuNode : null ,
					skuEditIndex: undefined
				},
				sets: {
					datas: {
						currentProduct: null					
					},
					openSetWindow: function(rowIndex){
						$('#productSetWindow').dialog('open');
						$('.product-set-container').html('');
						app_product_list.sets.datas.currentProduct = $('#product-datagrid').datagrid('getRows')[rowIndex];
						
						if(app_product_list.sets.datas.currentProduct.productSets && app_product_list.sets.datas.currentProduct.productSets.length > 0){
							
							$.each(app_product_list.sets.datas.currentProduct.productSets, function(index, setItem) {
								
								app_product_list.sets.addItem();
								$(`#product-set-item-${index}`).form('load', setItem);
								
							});
							
						}
					},
					addItem: function(){
						var setItemSize = $('.product-set-container .product-set-item').size();
						var _html = `<form class="product-set-item" id="product-set-item-${setItemSize}">
										<input name="setTitle" class="easyui-textbox" style="width: 290px;" prompt="套餐名称...">
										<input name="setPrice" class="easyui-numberbox" style="width: 80px;" data-options="min:0,precision:0"  prompt="套餐总价...">
										<input name="setNumber" class="easyui-numberspinner" value="${setItemSize + 1}" data-options="increment:1, min: 1, max: 99" style="width:60px;">
										<span class="fa fa-trash-o product-set-item-delete" onclick="$(this).parent().remove()"></span>
									</form>`
						
						$('.product-set-container').append(_html);
						$.parser.parse(`#product-set-item-${setItemSize}`); 
					},
					saveItems: function(){
						var setItemSize = $('.product-set-container .product-set-item').size();
						var setParams = [];
						for(var i = 0 ; i < setItemSize ; i++){
							setParams.push($(`#product-set-item-${i}`).serializeJson());
						}
						requestBodyServer(commonConfig.shopUrlPrefix() + '/product/sets', 'PUT', {'productId': app_product_list.sets.datas.currentProduct.id, 'productSets': setParams}).then((response) => {
							if (response.code == 1) {
								$('#productSetWindow').dialog('close');
								app_product_list.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					}
				},
				methods : {
					initCategoryTree: function(){
						$('#category-tree').tree({
						    url: commonConfig.shopUrlPrefix() + '/category/tree-list',
						    method: 'GET',
						    loadFilter: function(data,parent){
								if(data && data.code == 1){
									var treeRoot = {'text' : '全部分类'};
									if(data.datas.length == 0){
										return [treeRoot];
									}else{
										var _treeData = [] ; 
										$.each(data.datas, function(index , treeData) {
											var _tmpData = {
											 		id: treeData.id,
											 		text: treeData.name,
											 		attributes: {
											 			parentId: treeData.parentId,
											 			priority: treeData.priority,
											 			comments: treeData.comments
											 		}
											};
											var _tmpDataChildren = app_product_list.methods.findTreeChildrens(treeData);
											if(_tmpDataChildren){
												_tmpData.children = _tmpDataChildren ; 
											}
											 _treeData.push(_tmpData);
										});
										treeRoot.children = _treeData ; 
										return [treeRoot] ; 
									}
								}
								return [] ; 
							},
						    onSelect: function(node){
						    	app_product_list.methods.queryDatagrid();
						    },
						    onContextMenu: function(e, node){
								e.preventDefault();
								app_product_list.datas.contextMenuNode = node ; 
								$('#categoryMenu').menu('show', {
									left: e.pageX,
									top: e.pageY
								});
							}
						});
					},
					findTreeChildrens: function(treeDatas){
						if(!treeDatas.categories || treeDatas.categories.length == 0) return null ;
						var _children = [] ;
						$.each(treeDatas.categories, function(index , _temp) {
							var childrenNode = {
								id: _temp.id,
						 		text: _temp.name,
						 		attributes: {
						 			parentId: _temp.parentId,
						 			priority: _temp.priority,
						 			comments: _temp.comments
						 		}
							};
							var _tempChildren = app_product_list.methods.findTreeChildrens(_temp);
							if(_tempChildren){
								childrenNode.children = _tempChildren ; 
							}
							_children.push(childrenNode);
						});
						return _children ; 
					},
					categoryMenuHandler: function(item){
						if(item.name == 'add'){
							$('#categoryEditWin').window('open');
							$('#categoryEditForm').form('clear');
						}else if(item.name == 'edit'){
							$('#categoryEditWin').window('open');
							$('#categoryEditForm').form('clear');
							var _formData = {
								id: app_product_list.datas.contextMenuNode.id,
								name: app_product_list.datas.contextMenuNode.text,
								priority: app_product_list.datas.contextMenuNode.attributes.priority,
								comments: app_product_list.datas.contextMenuNode.attributes.comments,
								parentId: app_product_list.datas.contextMenuNode.attributes.parentId
							};
							$('#categoryEditForm').form('load' , _formData);
						}else if(item.name == 'delete'){
							$.messager.confirm('提示', '确定删除?删除不可恢复...', function(r){
								if (r){
									requestServer(commonConfig.shopUrlPrefix() + '/category/' + app_product_list.datas.contextMenuNode.id, 'DELETE').then((response) => {
										if (response.code == 1) {
											showMessage('<i class="fa fa-info-circle"></i>&nbsp; 删除成功...');
											$('#category-tree').tree('reload');
										}else {
											$.messager.alert('提示',response.message,'error');
										}
									}).catch((error) => {
										console.log(error)
									});
								}
							});
						}
					},
					editCategorySubimt: function(){
						var _formData = $('#categoryEditForm').serializeJson() ; 
						if(!_formData.parentId || _formData.parentId == ''){
							_formData.parentId = 0 ; 
							if(app_product_list.datas.contextMenuNode != null && app_product_list.datas.contextMenuNode.id > 0){
								_formData.parentId = app_product_list.datas.contextMenuNode.id;
							}
						}
						requestBodyServer(commonConfig.shopUrlPrefix() + '/category', 'POST', _formData).then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
								$('#category-tree').tree('reload');
								$('#categoryEditWin').window('close');
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					initSupplierCombo: function(){
						$('#supplierCombo').combobox({
						    url: commonConfig.shopUrlPrefix() + '/supplier/combobox',
						    valueField: 'id',
						    textField: 'text'
						});
					},
					createProduct : function(){
						var _productIds = $('#create-productIds').textbox('getText').replace(/[\r\n，]/g,",");
						var _sourceType = $('#create-sourceType').combobox('getValue') ;
						
						requestBodyServer(commonConfig.shopUrlPrefix() + '/product/create', 'POST', {'sourceType':_sourceType , 'productIds': _productIds.split(',')}).then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 后台处理中,预计需要'+_productIds.split(',').length+'分钟,请稍后查看...');
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					findSelectedTreeNodes: function(treeNodes){
						var _ids = [] ;
						if(!treeNodes || treeNodes.length == 0) return _ids;
						$.each(treeNodes , function(index , treeNode){
					        if(treeNode.id && treeNode.id >= 0){
					            _ids.push(treeNode.id);
					        }
							if(treeNode.children && treeNode.children.length > 0){
				            	var _childrenIds = app_product_list.methods.findSelectedTreeNodes(treeNode.children);
						        $.each(_childrenIds , function(i , _tmpId){
						            _ids.push(_tmpId);
						        });
						    }
					   });
					   return _ids;
					},
					initDatagridQueryParams: function(){
						var params = $('#productDatagridQueryParams').serializeArray();
						var queryParams = {};
						$.each(params , function(index , param){
						     queryParams[param.name] = param.value;
						})
						var time = $('#product-datepicker').val();
						queryParams.begainTime = timestamp(time.substring(0, 19));
						queryParams.endTime = timestamp(time.substring(22));
						
						queryParams.productId = queryParams.productId.replace(/[\r\n，]/g,",");
						
						var categoryNode = $('#category-tree').tree('getSelected') ; 
						if(categoryNode){
							if(categoryNode.id && categoryNode.id > 0){
								queryParams.categoryIds = app_product_list.methods.findSelectedTreeNodes([categoryNode]).join(',') ;
							}
						}
						return queryParams;
					},
					initTimeSelect: function(){
						$('#product-datepicker').daterangepicker($.extend(true, globalDaterangepickerOptions, {startDate: moment().startOf('day').subtract(29, 'days')}));
					},
					initDatagrid : function(){
						$('#product-datagrid').datagrid({
							height: $(document).height() - 260,
						    url: commonConfig.shopUrlPrefix() + '/product/list',
						    queryParams: {
								begainTime: timestamp($('#product-datepicker').val().substring(0, 19)),
								endTime: timestamp($('#product-datepicker').val().substring(22))
							},
						    columns:[[
						    	{field:'ck',checkbox:true,align:'center'},
								{field:'id',title:'ID',width:50,align:'center'},
								{field:'title',title:'标题',width:120,align:'center'},
								{field:'image',title:'主图',width:60,align:'center',formatter: function(value,row,index){
										if(row.coverImg){
											return '<a style="position: relative;width: 60px;height: 60px;display: inline-block;" href="http://www.buyfunshop.com/item/details.html?id='+row.id+'&source=admin" target="_blank"><img class="td-img" style="width: 60px;position: absolute;top: 0px;left: 0px;" src="'+ value +'"><img class="td-img" style="width: 60px;position: absolute;top: 0px;left: 0px;" src="'+ row.coverImg +'"></a>';
										}
										return '<a href="http://www.buyfunshop.com/item/details.html?id='+row.id+'&source=admin" target="_blank"><img class="td-img" src="'+ value +'"></a>';
									}
							},
								{field:'price',title:'售价',width:80,align:'center',formatter: function(value,row,index){
										return '<span style="color:red;font-weight: bold;">'+value+'<del style="margin-left: 4px;font-size: 10px;opacity: 0.5; color:#333">'+row.originalPrice+'<del><span>';
									}},
								{field:'statusName',title:'状态',width:60,align:'center',formatter: function(value,row,index){
									if(value == '上线中') return '<span class="success-text">'+value+'</span>';
									if(value == '已下线') return '<span class="warning-text">'+value+'</span>';
									if(value == '创建失败') return '<span class="error-text">'+value+'</span>';
									if(value == '创建中') return '<span class="info-text">'+value+'</span>';
									if(value == '创建成功') return '<span class="primary-text">'+value+'</span>';
								}},
								{field:'sourceType',title:'来源',width:50,align:'center'},
								{field:'supplierName',title:'供应商',width:100,align:'center',formatter: function(value,row,index){
										return '<a href="'+row.sourceUrl+'" target="_blank">'+value+'</a>';
									}},
								{field:'comments',title:'备注',width:100,align:'center'},
								{field:'sets',title:'套餐',width:150,align:'center',formatter: function(value,row,index){
									
									if(row.productSets && row.productSets.length > 0){
										
										var _html = ``;
										
										$.each(row.productSets, function(index, setItem) {
											
											_html += `<div style="display: flex; height: 24px; align-items: center;">
														<span style="font-weight: bold; width: 50px;">[${setItem.setPrice}]</span>
														<span style="font-weight: bold; width: 30px; color: #FF0000">[${setItem.setNumber}]</span>
														<span style="overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical;">${setItem.setTitle}</span>
													  </div>`
										});
										
										return _html ;
										
									}
									return '--';
								}},
								{field:'options',title:'操作',width:200,align:'center',formatter: function(value,row,index){
									   var _html =  '<button class="row-btn" onclick="app_product_list.sets.openSetWindow('+index+');">套餐</button>'+
									   				'<button class="row-btn warning" onclick="app_product_list.methods.copyProduct('+row.id+');">复制</button>'+
									   				'<button class="row-btn info" onclick="app_product_list.methods.editProduct('+row.id+');">编辑</button>'+
									   				'<button class="row-btn primary" onclick="app_product_list.methods.deleteProduct('+row.id+');">删除</button>'+
									   				'<button class="row-btn warning" onclick="app_product_list.methods.commentsProduct('+row.id+');">评价</button>';
									   
									   if(row.status){
										   	if(row.status == 1 || row.status == -10){
										   		_html += '<button class="row-btn success" onclick="app_product_list.methods.upProduct('+row.id+');">上线</button>'
										   	}else if(row.status == 10){
										   		_html += '<button class="row-btn error" onclick="app_product_list.methods.downProduct('+row.id+');">下线</button>'
										   	}
									   }
									   return _html ; 
									}
								}
								
						    ]]
						});
					},
					queryDatagrid: function(){
						$('#product-datagrid').datagrid('reload',app_product_list.methods.initDatagridQueryParams());
					},
					batchEditParame: function(){
						var products = $('#product-datagrid').datagrid('getChecked');
						if(products.length == 0){
							showMessage('请选择商品···')
							return
						}
						app_product_list.datas.selectBatchEditIds = products
						$('#productBatchParame').dialog('open');
						$('.product-cover-img').attr('src' , 'dists/imgs/upload_placeholder.png');
						
						$('#batchEditProductCategoryId').combotree({
						    url: commonConfig.shopUrlPrefix() + '/category/tree-list',
						    method: 'GET',
						    loadFilter: function(data,parent){
								if(data && data.code == 1){
									var treeRoot = {'text' : '全部分类', 'id': ''};
									if(data.datas.length == 0){
										return [treeRoot];
									}else{
										var _treeData = [] ; 
										$.each(data.datas, function(index , treeData) {
											var _tmpData = {
											 		id: treeData.id,
											 		text: treeData.name,
											 		attributes: {
											 			parentId: treeData.parentId,
											 			priority: treeData.priority,
											 			comments: treeData.comments
											 		}
											};
											var _tmpDataChildren = app_product_list.methods.findTreeChildrens(treeData);
											if(_tmpDataChildren){
												_tmpData.children = _tmpDataChildren ; 
											}
											 _treeData.push(_tmpData);
										});
										treeRoot.children = _treeData ; 
										return [treeRoot] ; 
									}
								}
								return [] ; 
							},
							onBeforeSelect: function(node){
								if(node.id && node.id != '' && node.children && node.children.length > 0) return false;
							}
						});
					},
					batchEditUploadCoverCallBack: function(result){
						$('.product-cover-img').attr('src' , JSON.parse(result.response).datas[0]);
					},
					findTreeChildrens: function(treeDatas){
						if(!treeDatas.categories || treeDatas.categories.length == 0) return null ;
						var _children = [] ;
						$.each(treeDatas.categories, function(index , _temp) {
							var childrenNode = {
								id: _temp.id,
						 		text: _temp.name,
						 		attributes: {
						 			parentId: _temp.parentId,
						 			priority: _temp.priority,
						 			comments: _temp.comments
						 		}
							};
							var _tempChildren = app_product_list.methods.findTreeChildrens(_temp);
							if(_tempChildren){
								childrenNode.children = _tempChildren ; 
							}
							_children.push(childrenNode);
						});
						return _children ; 
					},
					saveBatchEditParame: function(){
						var edit_parame =  $(".batchEditProductForm").serializeJson()
						if(!app_product_list.datas.selectBatchEditIds){
							return
						}
						if(edit_parame.description == '' && edit_parame.originalPrice == ''&& edit_parame.price == ''&& edit_parame.tags == ''&& edit_parame.title == ''){
							showMessage('内容不可以为空···')
							return
						}
						if(edit_parame.originalPrice - edit_parame.price < 0){
							showMessage('价格设置异常···')
							return
						}
						
						var _imgCover = $('.product-cover-img').attr('src') ; 
						if(_imgCover && _imgCover != 'dists/imgs/upload_placeholder.png'){
							edit_parame.coverImg = $('.product-cover-img').attr('src');
						}
						
						var params = []
						app_product_list.datas.selectBatchEditIds.map(function(e){
							params.push(Object.assign({
								id: e.id,
							},edit_parame))
						})
						requestServer(commonConfig.shopUrlPrefix() + '/product/batchEdit', 'PUT', JSON.stringify(params)).then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 批量编辑成功...');
								app_product_list.methods.queryDatagrid();
								$('#productBatchParame').dialog('close');
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					deleteProduct: function(productId){
						$.messager.confirm('提示', '确定删除?删除不可恢复...', function(r){
							if (r){
								requestServer(commonConfig.shopUrlPrefix() + '/product/' + productId, 'DELETE').then((response) => {
									if (response.code == 1) {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 删除成功...');
										app_product_list.methods.queryDatagrid();
									}else {
										$.messager.alert('提示',response.message,'error');
									}
								}).catch((error) => {
									console.log(error)
								});
							}
						});
					},
					upProduct: function(productId){  //status : -1 , 0 , 
						requestServer(commonConfig.shopUrlPrefix() + '/product/' + productId + '/up', 'PUT').then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 上架成功...');
								app_product_list.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					downProduct: function(productId){  //status : -1 , 0 , 
						var productIds = [productId] ; 
						requestServer(commonConfig.shopUrlPrefix() + '/product/downs', 'PUT' , JSON.stringify(productIds)).then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 操作完成...');
								app_product_list.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					upProducts: function(){
						var products = $('#product-datagrid').datagrid('getChecked');
						var productIds = [] ; 
						$.each(products, function(index , product) {
							productIds.push(product.id);
						});
						requestServer(commonConfig.shopUrlPrefix() + '/product/ups', 'PUT' , JSON.stringify(productIds)).then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 操作完成...');
								app_product_list.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					downProducts: function(){
						var products = $('#product-datagrid').datagrid('getChecked');
						var productIds = [] ; 
						$.each(products, function(index , product) {
							productIds.push(product.id);
						});
						requestServer(commonConfig.shopUrlPrefix() + '/product/downs', 'PUT' , JSON.stringify(productIds)).then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 操作完成...');
								app_product_list.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					editProduct: function(productId){
						requestServer(commonConfig.shopUrlPrefix() + '/product/' + productId, 'GET').then((response) => {
							if (response.code == 1) {
								app_product_list.datas.editProduct = response.datas;
								$('#productEdit').window('open');
								app_product_list.methods.initCategoryComboTree();
								app_product_list.methods.initProductTexts();
								app_product_list.methods.initProductImages();
								app_product_list.methods.initProductPropsEdit();
								app_product_list.methods.initProductDetailsEdit();
								app_product_list.methods.initProductAttributes();
								app_product_list.methods.initProductSkuDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					copyProduct: function(productId){
						requestBodyServer(commonConfig.shopUrlPrefix() + `/product/${productId}/copy`, 'PUT').then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 复制成功');
								app_product_list.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					commentsProduct: function(productId){
						$('#productComments').window('open');
						$('#product-comments-datagrid').datagrid({
						    url: commonConfig.shopUrlPrefix() + '/product/'+ productId +'/comments',
						    pagination: false,
						    toolbar: [{
								text: '新增',
								handler: function(){
									$('#productCommentsPersit').window('open');
									$('#productCommentsPersit-form').form('clear');
									app_product_list.datas.commentsProductId = productId ;
								}
							},'-',{
								text: '删除',
								handler: function(){
									var products = $('#product-comments-datagrid').datagrid('getChecked');
									var productIds = [] ; 
									$.each(products, function(index , product) {
										productIds.push(product.id);
									});
									requestServer(commonConfig.shopUrlPrefix() + '/product/comments', 'DELETE' , JSON.stringify(productIds)).then((response) => {
										if (response.code == 1) {
											showMessage('<i class="fa fa-info-circle"></i>&nbsp; 操作完成...');
											$('#product-comments-datagrid').datagrid('reload');
										}else {
											$.messager.alert('提示',response.message,'error');
										}
									}).catch((error) => {
										console.log(error)
									});
								}
							}],
						    columns:[[
						    	{field:'ck',checkbox:true,align:'center'},
								{field:'userName',title:'名称',width:100,align:'center'},
								{field:'comments',title:'评论',width:300,align:'center'},
								{field:'images',title:'图片',width:100,align:'center',formatter: function(value,row,index){
									return  (value && value != '') ? '<img class="td-img" src="'+ value +'">' : '--';
								}},
								{field:'createdAt',title:'时间',width:150,align:'center',formatter: function(value,row,index){
									return FormatDate(value);
								}}
								
						    ]]
						});
					},
					productCommentsPersit: function(){
						var _params = $('#productCommentsPersit-form').serializeJson();
						var _imgCover = $('.product-comments-img').attr('src') ; 
						if(_imgCover && _imgCover != 'dists/imgs/upload_placeholder.png'){
							_params.images = $('.product-comments-img').attr('src');
						}
						if(!_params.userName || _params.userName == ''){
							showMessage('用户名不可以为空···')
							return;
						}
						if(!_params.comments || _params.comments == ''){
							showMessage('评论不可以为空···')
							return;
						}
						if(!_params.commentsAt || _params.commentsAt == ''){
							showMessage('时间不可以为空···')
							return;
						}
						_params.productId = app_product_list.datas.commentsProductId;
						
						requestServer(commonConfig.shopUrlPrefix() + '/product/comments', 'POST', JSON.stringify(_params)).then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 操作完成...');
								$('#product-comments-datagrid').datagrid('reload');
								$('#productCommentsPersit-form').form('clear');
								$('.product-comments-img').attr('src', 'dists/imgs/upload_placeholder.png')
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
						
					},
					initCategoryComboTree: function(){
						$('#categoryId').combotree({
						    url: commonConfig.shopUrlPrefix() + '/category/tree-list',
						    method: 'GET',
						    loadFilter: function(data,parent){
								if(data && data.code == 1){
									var treeRoot = {'text' : '全部分类', 'id': ''};
									if(data.datas.length == 0){
										return [treeRoot];
									}else{
										var _treeData = [] ; 
										$.each(data.datas, function(index , treeData) {
											var _tmpData = {
											 		id: treeData.id,
											 		text: treeData.name,
											 		attributes: {
											 			parentId: treeData.parentId,
											 			priority: treeData.priority,
											 			comments: treeData.comments
											 		}
											};
											var _tmpDataChildren = app_product_list.methods.findTreeChildrens(treeData);
											if(_tmpDataChildren){
												_tmpData.children = _tmpDataChildren ; 
											}
											 _treeData.push(_tmpData);
										});
										treeRoot.children = _treeData ; 
										return [treeRoot] ; 
									}
								}
								return [] ; 
							},
							onBeforeSelect: function(node){
								if(node.id && node.id != '' && node.children && node.children.length > 0) return false;
							}
						});
					},
					initProductTexts : function(){
						var _formData = {
							'title': app_product_list.datas.editProduct.title,
							'price': app_product_list.datas.editProduct.price,
							'originalPrice': app_product_list.datas.editProduct.originalPrice,
							'description': app_product_list.datas.editProduct.description,
							'tags': app_product_list.datas.editProduct.tags,
							'sourceNumber': app_product_list.datas.editProduct.productExtEditDTO.sourceNumber,
							'sourceUrl': app_product_list.datas.editProduct.productExtEditDTO.sourceUrl,
							'comments': app_product_list.datas.editProduct.productExtEditDTO.comments,
							'categoryId': app_product_list.datas.editProduct.productExtEditDTO.categoryId || ''
						} ;
						$('.productInfo-text > form').form('load',_formData);
					},
					initProductImages : function(){
						$('.productInfo .productInfo-images').html('');
						var _carouselImages = '';
						$.each(app_product_list.datas.editProduct.productExtEditDTO.carouselImages.split(';'), function(index , carouselImage) {
							_carouselImages += '	<div class="img-con"><img src="'+carouselImage+'" /></div>';
						});
						
						var _html = '<img class="primary" src="'+app_product_list.datas.editProduct.image+'" />'+
									'<a class="image-delete"><i class="fa fa-trash-o"></i></a>' +
									'<div class="images">'+
									_carouselImages +
									'<div class="img-con-add"><i class="fa fa-plus"></div>'
									'</div>';
						
						$('.productInfo .productInfo-images').html(_html);
						
						// 在这里处理图片拖拽
						$('.productInfo .productInfo-images div.images').DDSort({
						    target: 'div',
						    floatStyle: {'border': '1px solid #ccc', 'background-color': '#fff'},
						    cloneStyle: {'background-color': '#ff0000'}
						});
						
						app_product_list.events.productInfoImagesClickEvent();
						
						$('.productInfo .productInfo-images .img-con-add').click(function(){
							app_product_list.datas.uploaderUploadCallBack = app_product_list.methods.productImageAddCallBack;
							$('#prodfuctChangeImage').trigger('click');
						});
						$('.productInfo .productInfo-images img.primary').click(function(){
							app_product_list.datas.uploaderUploadCallBack = app_product_list.methods.productImageChangeCallBack;
							$('#prodfuctChangeImage').trigger('click');
						});
						$('.productInfo .productInfo-images div.images img').eq(0).trigger('click');
						$('.productInfo .productInfo-images a.image-delete').click(function(){
							$.messager.confirm('提示', '确定删除?删除不可恢复...', function(r){
								if (r){
									$('.productInfo .productInfo-images div.images img.active').remove();
									$('.productInfo .productInfo-images div.images img').eq(0).trigger('click');
								}
							});
						});
					},
					productImageChangeCallBack: function(result){
						$('.productInfo .productInfo-images div.images img.active').attr('src' , JSON.parse(result.response).datas[0]);
                    	$('.productInfo .productInfo-images div.images img.active').trigger('click');
					},
					// 新上传的图片需要监听事件
					productImageAddCallBack: function(result){
						$('.productInfo .productInfo-images div.images .img-con-add').before('<div class="img-con"><img src="'+ JSON.parse(result.response).datas[0] +'" /></div>');
						
						app_product_list.events.productInfoImagesClickEvent();
                    	
                    	$('.productInfo .productInfo-images div.images .img-con-add').prev().children('img').trigger('click')
					},
					initUpload: function () {
	                    var uploaderUpload = new plupload.Uploader({
	                        runtimes: 'html5,html4',
	                        browse_button: 'prodfuctChangeImage',
	                        url: commonConfig.shopUrlPrefix() + '/upload/image',
	                        file_data_name: 'images',
	                        filters: {
	                            max_file_size: '2048kb',
	                            mime_types: [
	                                {title : "Image files", extensions : "jpg,gif,png,jpeg"}
	                            ],
	                        },
	                        multipart_params: {
	                            //access_token: utils.cookie.getCookie('accessToken')
	                        },
	                        init: {
	                            FilesAdded: function (up, files) {
	                            	tools.showLoading();
	                                up.start();
	                            },
	                            FileUploaded: function(up, files, result){
	                            	app_product_list.datas.uploaderUploadCallBack(result);
	                            	tools.hideLoading();
                            	},
	                            Error: function (up, err) {
	                            	tools.hideLoading();
	                            	if(typeof(err) == 'object'){
		                        		$.messager.alert('提示',err.message,'error');
		                        	}else{
		                        		$.messager.alert('提示',JSON.parse(err.response).body.message,'error');
		                        	}
	                            }
	                        }
	                    });
	                    uploaderUpload.init();
	               	},
	               	initProductPropsEdit: function(){
	               		if(!app_product_list.datas.propEditor){
							var E = window.wangEditor;
	       		 			app_product_list.datas.propEditor = new E('.productProps');
	       		 			app_product_list.datas.propEditor.customConfig.menus = ['head','bold','fontSize','fontName','italic','underline','strikeThrough','foreColor','backColor','justify','quote','table','undo','redo'];
	        				app_product_list.datas.propEditor.create();
						}
						app_product_list.datas.propEditor.txt.html(app_product_list.datas.editProduct.productExtEditDTO.productProps || '');
	               	},
					initProductDetailsEdit: function(){
						if(!app_product_list.datas.editor){
							var E = window.wangEditor;
	       		 			app_product_list.datas.editor = new E('.productDetails');
	       		 			app_product_list.datas.editor.customConfig.menus = ['head','bold','fontSize','fontName','italic','underline','strikeThrough','foreColor','backColor','justify','quote','image','video','undo','redo'];
	       		 			app_product_list.datas.editor.customConfig.uploadImgServer = commonConfig.shopUrlPrefix() + '/upload/image';
	       		 			app_product_list.datas.editor.customConfig.uploadImgMaxSize = 5000 * 1024 * 1024;
	       		 			app_product_list.datas.editor.customConfig.uploadImgMaxLength = 200;
	       		 			app_product_list.datas.editor.customConfig.uploadImgTimeout = 500 * 1000;
	       		 			app_product_list.datas.editor.customConfig.uploadFileName = 'images';
	       		 			app_product_list.datas.editor.customConfig.uploadImgHooks = {
							    // 上传图片之前
							    before: function(xhr) {
							    	tools.showLoading();
							    },
							    success: function(xhr) {
							        tools.hideLoading();
							    },
							    // 图片上传并返回了结果，但图片插入时出错了
							    fail: function(xhr, editor, resData) {
							       	tools.hideLoading();
							       	$.messager.alert('提示','上传失败....','error');
							    },
							    // 上传图片出错，一般为 http 请求的错误
							    error: function(xhr, editor, resData) {
							        tools.hideLoading();
							        $.messager.alert('提示','上传出错....','error');
							    },
							    // 上传图片超时
							    timeout: function(xhr) {
							    	tools.hideLoading();
							        $.messager.alert('提示','上传超时....','error');
							    }
							}
	        				app_product_list.datas.editor.create();
						}
						app_product_list.datas.editor.txt.html(app_product_list.datas.editProduct.productExtEditDTO.productDetails);
						
					},
					initProductAttributes: function(){
						$('.productAttribute').html('');
						$.each(app_product_list.datas.editProduct.productAttributeEditDTOs, function(index , productAttributeEditDTO) {
							var _html = '<div class="attribute-panel">'+
										'	<div class="attribute-panel-header">'+
										'		<span attributeId="'+productAttributeEditDTO.id+'" onclick="app_product_list.methods.changeAttributeName(this)">'+productAttributeEditDTO.name+'</span>'+
										'	</div>'+
										'	<div class="attribute-panel-body">'+
										'		<input type="text" attributeId="'+productAttributeEditDTO.id+'" class="form-control tags-'+productAttributeEditDTO.id+'" name="tags" />'+
										'	</div>'+
										'</div>' ;
							$('.productAttribute').append(_html);
							var _tags = [] , _sourceTags=[]; 
							$.each(productAttributeEditDTO.productAttributeValueEditDTOs, function(index , productAttributeValueEditDTO) {
								_sourceTags.push(productAttributeValueEditDTO.id + '@#@' + productAttributeValueEditDTO.value);
								_tags.push(productAttributeValueEditDTO.value);
							});
							$('.productAttribute input.tags-'+productAttributeEditDTO.id).inputTags({sourceTags : _sourceTags, tags : _tags , minLength : 1 , maxLength: 200 ,max: 200 , 
								myfocus: function($elem){
									var _attrValue = $('.inputTags-list > .inputTags-item.is-edit').attr('data-tag');
									$('#productSku-datagrid').datagrid('uncheckAll');
									$.each($('#productSku-datagrid').datagrid('getRows') ,function(index, row){
									    var tmps = row.name.split('-');
									    if(tmps[0] == _attrValue || tmps[1] == _attrValue){
									       $('#productSku-datagrid').datagrid('checkRow', index);
									    }
									})
								},
								create: function($elem) {
									// 商品增加属性,当属性增加完成之后需要刷新页面.
									var _params = {
										productId: app_product_list.datas.editProduct.id,
										attributeValueText: $elem.tags[$elem.tags.length - 1],
										attributeId: $elem.$element.attr('attributeid')
									};
									
									requestBodyServer(commonConfig.shopUrlPrefix() + '/product/attributevalue', 'POST', _params).then((response) => {
										if (response.code == 1) {
											showMessage('<i class="fa fa-info-circle"></i>&nbsp; 新增成功,页面将在刷新后继续...');
											$('#productEdit').window('close');
											app_product_list.methods.editProduct(_params.productId);
										}else {
											$.messager.alert('提示',response.message,'error');
										}
									}).catch((error) => {
										console.log(error)
									});
									
							    },
								update: function($elem){
									//寻找差异数据
									var updateIndex = -1 ;
									for(var i = 0 ; i < $elem.tags.length ; i++){
										if($elem.options.tags[i] != $elem.tags[i]){
											updateIndex = i ; 
											break;
										}
									}
									if(updateIndex < 0) return false;
									
									var attributesplit = $elem.options.sourceTags[updateIndex].split('@#@');//attributesplit[0]==>id , attributesplit[1]==>值
									var newAttributeValue = $elem.tags[updateIndex];
									
									$.each(app_product_list.datas.editProduct.productSkuEditDTOs, function(index , productSkuDTO) {
										if(productSkuDTO.productAttributeValueId1 == attributesplit[0] || productSkuDTO.productAttributeValueId2 == attributesplit[0]){
											productSkuDTO.name = productSkuDTO.name.replace(attributesplit[1].replace("-", "~").replace("/", "#") , newAttributeValue).replace(attributesplit[1] , newAttributeValue);
										}
									});
									$elem.options.tags[updateIndex] = newAttributeValue ; 
									$elem.options.sourceTags[updateIndex] = attributesplit[0] + '@#@' + newAttributeValue ; 
									
									//同步到editProduct
									$.each(app_product_list.datas.editProduct.productAttributeEditDTOs, function(index , productAttributeEditDTO) {
										$.each(productAttributeEditDTO.productAttributeValueEditDTOs, function(index2 , productAttributeValueEditDTO) {
											if(productAttributeValueEditDTO.id == attributesplit[0]){
												productAttributeValueEditDTO.value = newAttributeValue ; 
											}
										});
									});
									
									$('#productSku-datagrid').datagrid('loadData' , app_product_list.datas.editProduct.productSkuEditDTOs);
								},
								destroy: function($elem){
									var updateIndex = -1; //这里找到的I是被删除的
									if($elem.tags.length == 0){
										updateIndex = 0 ; 
									}else{
										for(var i = 0 ; i < $elem.options.tags.length ; i++){
											if($elem.options.tags[i] != $elem.tags[i]){
												updateIndex = i ; 
												break;
											}
										}
									}
									if(updateIndex < 0) return false;
									var attributesplit = $elem.options.sourceTags[updateIndex].split('@#@');//attributesplit[0]==>id , attributesplit[1]==>值
									var _productSkuEditDTOs = [] ; 
									$.each(app_product_list.datas.editProduct.productSkuEditDTOs, function(index , productSkuDTO) {
										if(productSkuDTO.productAttributeValueId1 != attributesplit[0] && productSkuDTO.productAttributeValueId2 != attributesplit[0]){
											_productSkuEditDTOs.push(productSkuDTO);
										}
									});
									
									$elem.options.tags.splice(updateIndex, 1);
									$elem.options.sourceTags.splice(updateIndex, 1);
									app_product_list.datas.editProduct.productSkuEditDTOs = _productSkuEditDTOs ; 
									
									//同步到editProduct
									$.each(app_product_list.datas.editProduct.productAttributeEditDTOs, function(index , productAttributeEditDTO) {
										for(var i = 0 ; i < productAttributeEditDTO.productAttributeValueEditDTOs.length ; i++){
											if(productAttributeEditDTO.productAttributeValueEditDTOs[i].id == attributesplit[0]){
												productAttributeEditDTO.productAttributeValueEditDTOs.splice(i, 1);
												i--;
											}
										}
									});
									
									$('#productSku-datagrid').datagrid('loadData' , app_product_list.datas.editProduct.productSkuEditDTOs);
								}
							});
						});
					},
					changeAttributeName: function(target){
						$.messager.prompt('属性', '属性名:', function(r){
							if (r){
								$(target).html(r.trim());
								$.each(app_product_list.datas.editProduct.productAttributeEditDTOs, function(index, productAttributeEditDTO) {
									if(productAttributeEditDTO.id == $(target).attr('attributeId')){
										productAttributeEditDTO.name = r.trim();
									}
								});
							}
						});
					},
					productSkuImageChangeCallBack: function(result){
                    	var _checkedRow = $('#productSku-datagrid').datagrid('getChecked');
                    	$.each(_checkedRow, function(index, checkedRow) {
							$.each(app_product_list.datas.editProduct.productSkuEditDTOs, function(index , productSkuDTO) {
								if(productSkuDTO.id == checkedRow.id){
									productSkuDTO.image = JSON.parse(result.response).datas[0] ; 
								}
							});
						});
						$('#productSku-datagrid').datagrid('loadData' , app_product_list.datas.editProduct.productSkuEditDTOs);
					},
					initProductSkuDatagrid: function(){
						$('#productSku-datagrid').datagrid({
							data: app_product_list.datas.editProduct.productSkuEditDTOs,
							toolbar: [{
								text: 'SKU图',
								iconCls: 'fa fa-edit',
								handler: function(){
									var _checkedRow = $('#productSku-datagrid').datagrid('getChecked');
									if(_checkedRow.length == 0){
										$.messager.alert('提示','请选择要修改的SKU...');
										return ;
									}
									app_product_list.datas.uploaderUploadCallBack = app_product_list.methods.productSkuImageChangeCallBack;
									$('#prodfuctChangeImage').trigger('click');
								}
							},'-',{
								text: '库存',
								iconCls: 'fa fa-edit',
								handler: function(){
									var _checkedRow = $('#productSku-datagrid').datagrid('getChecked');
									if(_checkedRow.length == 0){
										$.messager.alert('提示','请选择要修改的SKU...');
										return ;
									}
									$.messager.prompt('库存', '库存:', function(inputValue){
										if (inputValue){
											$.each(_checkedRow, function(index, checkedRow) {
												$.each(app_product_list.datas.editProduct.productSkuEditDTOs, function(index , productSkuDTO) {
													if(productSkuDTO.id == checkedRow.id){
														productSkuDTO.inventory = inputValue ; 
													}
												});
											});
											$('#productSku-datagrid').datagrid('loadData' , app_product_list.datas.editProduct.productSkuEditDTOs);
										}
									});
								}
							},'-',{
								text: '售价',
								iconCls: 'fa fa-edit',
								handler: function(){
									var _checkedRow = $('#productSku-datagrid').datagrid('getChecked');
									if(_checkedRow.length == 0){
										$.messager.alert('提示','请选择要修改的SKU...');
										return ;
									}
									$.messager.prompt('售价', '售价:', function(inputValue){
										if (inputValue){
											$.each(_checkedRow, function(index, checkedRow) {
												$.each(app_product_list.datas.editProduct.productSkuEditDTOs, function(index , productSkuDTO) {
													if(productSkuDTO.id == checkedRow.id){
														productSkuDTO.price = inputValue ; 
													}
												});
											});
											$('#productSku-datagrid').datagrid('loadData' , app_product_list.datas.editProduct.productSkuEditDTOs);
										}
									});
								}
							},'-',{
								text: '采购价',
								iconCls: 'fa fa-edit',
								handler: function(){
									var _checkedRow = $('#productSku-datagrid').datagrid('getChecked');
									if(_checkedRow.length == 0){
										$.messager.alert('提示','请选择要修改的SKU...');
										return ;
									}
									$.messager.prompt('采购价', '采购价:', function(inputValue){
										if (inputValue){
											$.each(_checkedRow, function(index, checkedRow) {
												$.each(app_product_list.datas.editProduct.productSkuEditDTOs, function(index , productSkuDTO) {
													if(productSkuDTO.id == checkedRow.id){
														productSkuDTO.purchasePrice = inputValue ; 
													}
												});
											});
											$('#productSku-datagrid').datagrid('loadData' , app_product_list.datas.editProduct.productSkuEditDTOs);
										}
									});
								}
							}],
							pagination:false,
							idField: 'id',
						    columns:[[
						    	{field:'ck',checkbox:true,align:'center'},
						    	{field:'image',title:'SKU图',width:60,align:'center',formatter:function(value,row,index){
						    		return '<img class="td-img" onmouseover="tools.bigImg(this)" onmouseout="tools.normalImg()" src="'+ value +'">';
						    	}},
								{field:'barcode',title:'编码',width:100,align:'center'},
								{field:'name',title:'名称',width:150,align:'center', editor: 'text'},
								{field:'inventory',title:'库存',width:50,align:'center'},
								{field:'price',title:'售价',width:80,align:'center'},
								{field:'purchasePrice',title:'采购价',width:80,align:'center'},
						    ]],
						    onDblClickCell: function(index,field,value){
						    	if(app_product_list.datas.skuEditIndex != undefined){
						    		$(this).datagrid('endEdit', app_product_list.datas.skuEditIndex);
						    		app_product_list.datas.skuEditIndex = undefined;
						    	}
						    	app_product_list.datas.skuEditIndex = index ; 
								$(this).datagrid('beginEdit', index);
							}
						});
					},
					saveProduct: function(){
						$.messager.confirm('提示', '确定修改?修改后不可恢复...', function(r){
							if (r){
								
								//关闭正在编辑的SKU
								if(app_product_list.datas.skuEditIndex != undefined){
						    		$('#productSku-datagrid').datagrid('endEdit', app_product_list.datas.skuEditIndex);
						    	}
								
								app_product_list.datas.editProduct.title = $('#title').textbox('getText');
								app_product_list.datas.editProduct.description = $('#description').textbox('getText');
								app_product_list.datas.editProduct.originalPrice = $('#originalPrice').numberbox('getValue');
								app_product_list.datas.editProduct.tags = $('#tags').textbox('getText').replace(/，/g,',');
								app_product_list.datas.editProduct.image = $('.productInfo .productInfo-images .images img').eq(0).attr('src');
								app_product_list.datas.editProduct.productExtEditDTO.sourceNumber = $('#sourceNumber').textbox('getText');
								app_product_list.datas.editProduct.productExtEditDTO.sourceUrl = $('#sourceUrl').textbox('getText');
								app_product_list.datas.editProduct.productExtEditDTO.comments = $('#comments').textbox('getText');
								
								app_product_list.datas.editProduct.productExtEditDTO.categoryId = $('#categoryId').combotree('getValue');
								app_product_list.datas.editProduct.productExtEditDTO.productDetails = app_product_list.datas.editor.txt.html();
								app_product_list.datas.editProduct.productExtEditDTO.productProps = app_product_list.datas.propEditor.txt.html();
								var _carouselImages = [];
								var _carouselImagesDom = $('.productInfo .productInfo-images .images img');
								$.each(_carouselImagesDom , function(index, carouselImages){
								   _carouselImages.push($(carouselImages).attr('src'));
								});
								app_product_list.datas.editProduct.productExtEditDTO.carouselImages = _carouselImages.join(";");
								
								requestBodyServer(commonConfig.shopUrlPrefix() + '/product/edit', 'PUT', app_product_list.datas.editProduct).then((response) => {
									if (response.code == 1) {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 修改成功...');
										app_product_list.methods.queryDatagrid();
									}else {
										$.messager.alert('提示',response.message,'error');
									}
								}).catch((error) => {
									console.log(error)
								});
							}
						});
					}
				},
				events : {
					enterSearchEvent: function(){
						$("#productDatagridQueryParams").bind("keydown",function(e){
							// 兼容FF和IE和Opera
							var theEvent = e || window.event;
							var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
							if (code == 13) {
								//回车执行查询
								app_product_list.methods.queryDatagrid();
							}
						});
					},
					productInfoImagesClickEvent: function(){
						$('.productInfo .productInfo-images div.images img').click(function(){
							$('.productInfo .productInfo-images div.images img').removeClass('active');
							$(this).addClass('active');
							$('.productInfo .productInfo-images img.primary').attr('src' , $(this).attr('src'));	
						});
					}
				},
				init : function(){
					app_product_list.events.enterSearchEvent();
					app_product_list.methods.initCategoryTree();
					app_product_list.methods.initSupplierCombo();
					app_product_list.methods.initTimeSelect();
					app_product_list.methods.initDatagrid();
					app_product_list.methods.initUpload();
				}
			}
			app_product_list.init();
		</script>
	</body>
</html>
